﻿using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Serialization;

namespace MediaBot.Entities
{
    public class AjaxType
    {
        [XmlAttribute("requestUrl")]
        public string RequestUrl = string.Empty;

        [XmlElement("postData")]
        public MatchType PostData;

        private string _postData;

        public string GetData(XmlNode node, XmlNamespaceManager nsmng)
        {
            if (string.IsNullOrEmpty(RequestUrl) || PostData == null)
                return string.Empty;

            return this.DownloadPage(node, nsmng);
        }

        private string DownloadPage(XmlNode node, XmlNamespaceManager nsmng)
        {
            var retryStr = ConfigurationManager.AppSettings["Retry"];
            var retry = string.IsNullOrEmpty(retryStr) ? 3 : int.Parse(retryStr);

            _postData = PostData.GetString(node, nsmng);
            string content = null;
            //continue downloading if this page redirect to another page

            var runningTime = 0;
            while (runningTime < retry)
            {
                try
                {
                    runningTime++;

                    var httpRequest = (HttpWebRequest)WebRequest.Create(RequestUrl);
                    InitializeWebRequest(httpRequest);

                    var response = httpRequest.GetResponse();

                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        content = sr.ReadToEnd();
                    }

                    break;
                }
                catch (WebException ex)
                {
                    if (ex.Message.IndexOf("Server Unavailable", StringComparison.Ordinal) >= 0)
                        System.Threading.Thread.Sleep(60 * 1000);
                    else if (runningTime >= retry)
                        throw ex;
                }
                catch (Exception ex)
                {
                    if (runningTime >= retry)
                        throw ex;
                }
            }


            return content;
        }

        private void InitializeWebRequest(HttpWebRequest request)
        {
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36";
            request.KeepAlive = true;
            request.AllowAutoRedirect = true;

            if (_postData != string.Empty)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = WebRequestMethods.Http.Post;
                request.ContentLength = _postData.Length;


                using (var sw = new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(PostData);
                    sw.Close();
                }
            }
            else
                request.Method = WebRequestMethods.Http.Get;

        }
    }
}
